package com.jus.player.fragment.main;

import static com.jus.player.api.OkHttpHelper._DATA;
import static com.jus.player.util.CommonUtils.navigateTo;
import static com.jus.player.util.CommonUtils.showToast;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Build;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.jus.player.R;
import com.jus.player.activity.my.FeedbackActivity;
import com.jus.player.activity.my.HistoryActivity;
import com.jus.player.activity.my.RechargeActivity;
import com.jus.player.activity.my.SystemSetActivity;
import com.jus.player.activity.my.VipRechargeActivity;
import com.jus.player.api.ApiConfig;
import com.jus.player.api.OkHttpHelper;
import com.jus.player.config.AppConfig;
import com.jus.player.entity.UserBean;
import com.jus.player.fragment.BaseFragment;
import com.jus.player.util.CommonUtils;
import com.jus.player.util.DialogUtils;
import com.jus.player.util.StringUtils;

import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 * 我的页面
 */
public class MyFragment extends BaseFragment {

    private UserBean userBean;
    private ImageView mHeaderImg;
    private TextView nick;
    private TextView userAccount;
    private TextView balanceText;
    private TextView vipExpireDate;
    //观看历史
    private RelativeLayout playHistoryBtn;
    //意见反馈
    private RelativeLayout feedbackBtn;
    //系统设置
    private RelativeLayout btnSystemSet;
    //邀请好友
    private RelativeLayout inviteBtn;
    //退出登陆
    private RelativeLayout mLogoutBtn;
    // 充值
    private Button rechargeBtn;
    private Button vipRechargeBtn;

    public static MyFragment newInstance() {
        return new MyFragment();
    }

    @Override
    protected int initLayout() {
        return R.layout.fragment_my;
    }

    @Override
    protected void initView() {
        mHeaderImg = mRootView.findViewById(R.id.img_header);
        nick = mRootView.findViewById(R.id.nick);
        userAccount = mRootView.findViewById(R.id.user_account);
        balanceText = mRootView.findViewById(R.id.balance_text);
        vipExpireDate = mRootView.findViewById(R.id.expire_date);

        playHistoryBtn = mRootView.findViewById(R.id.btn_play_history);
        feedbackBtn = mRootView.findViewById(R.id.btn_feedback);
        inviteBtn = mRootView.findViewById(R.id.btn_invite);
        mLogoutBtn = mRootView.findViewById(R.id.rl_logout);
        rechargeBtn = mRootView.findViewById(R.id.btn_recharge);
        btnSystemSet = mRootView.findViewById(R.id.btn_system_set);
        vipRechargeBtn = mRootView.findViewById(R.id.vip_recharge_btn);

        playHistoryBtn.setOnClickListener(view -> navigateTo(requireActivity(), HistoryActivity.class));
        feedbackBtn.setOnClickListener(view -> navigateTo(requireActivity(), FeedbackActivity.class));
        inviteBtn.setOnClickListener(view -> showToast(requireActivity(), "功能正在完善中，敬请期待！"));
        //系统设置点击事件
        btnSystemSet.setOnClickListener(view -> navigateTo(requireActivity(), SystemSetActivity.class));
    }

    @Override
    protected void initData() {
        //获取用户信息
        this.getUserInfo();
        // 退出登录点击事件
        mLogoutBtn.setOnClickListener(v -> {
            DialogUtils.showConfirmDialog(getContext(), "确认退出登录？",
                    "退出后需要重新登录", () -> CommonUtils.logout(requireActivity()));
        });
        //充值点击事件
        rechargeBtn.setOnClickListener(v -> {
            Intent intent = new Intent(getActivity(), RechargeActivity.class);
            if (userBean != null) {
                intent.putExtra("balance", userBean.getBalance());
            }
            startActivity(intent);
        });
        //会员充值点击事件
        vipRechargeBtn.setOnClickListener(view ->
                navigateTo(requireActivity(), VipRechargeActivity.class));

    }


    @Override
    protected boolean isLazyLoad() {
        return true;
    }

    @Override
    public void onPause() {
        super.onPause();
        if (getActivity() != null) {
            getActivity().getWindow().getDecorView().setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
            );
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        if (userBean != null) {
            this.getUserInfo();
        }
        if (getActivity() != null) {
            getActivity().getWindow().getDecorView().setSystemUiVisibility(
                    View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR
            );
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (hidden) {
            onPause();
        } else {
            onResume();
        }
    }


    /**
     * 请求网络数据：我的页面信息-余额
     * * @param categoryId 分类ID
     */
    private void getUserInfo() {
        Map<String, String> map = new HashMap<>();
        OkHttpHelper.getInstance(requireActivity()).getAsync(ApiConfig.MY_INFO, map,
                new OkHttpHelper.HttpCallback() {
                    @SuppressLint("NotifyDataSetChanged")
                    @Override
                    public void onSuccess(String res) {
                        JSONObject jo = JSONObject.parseObject(res);
                        JSONObject userJo = jo.getJSONObject(_DATA);
                        userBean = JSON.to(UserBean.class, userJo);
                        CommonUtils.insertToSp(requireActivity(), AppConfig.SP_USER_ID, userBean.getId() + "");
                        requireActivity().runOnUiThread(() -> handleDataOnUiThread());
                    }

                    @Override
                    public void onFailure(OkHttpHelper.HttpException e) {
                        CommonUtils.showToastAsync(requireActivity(), e.getMessage());
                    }
                });
    }

    private void handleDataOnUiThread() {
        if (!StringUtils.isEmpty(userBean.getHeadThumbUrl())) {
            Glide.with(requireActivity())
                    .load(userBean.getHeadThumbUrl())
                    //.placeholder(android.R.color.white)//在图片加载前现实白色背景
                    .apply(RequestOptions.circleCropTransform())// 圆形裁剪
                    .into(mHeaderImg);
        }
        if (!StringUtils.isEmpty(userBean.getNickname())) {
            nick.setText(userBean.getNickname());
        }
        if (!StringUtils.isEmpty(userBean.getLoginAccount())) {
            userAccount.setText(userBean.getLoginAccount());
        }
        if (userBean.getVipExpire() != null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                vipExpireDate.setText(requireActivity().getString(R.string.vip_expire_time)
                        + userBean.getVipExpire().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"))
                        + requireActivity().getString(R.string.str_expire));
            }
        } else {
            vipExpireDate.setText(requireActivity().getString(R.string.not_subscribed_vip));
        }
        if (userBean.getBalance() != null) {
            balanceText.setText(String.valueOf(userBean.getBalance()));
        }
    }

}